package cn.edu.jnu.supershopper;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BookFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BookFragment extends Fragment {
    public static final int MENU_ID_ADD = 1;
    public static final int MENU_ID_UPDATE = 2;
    public static final int MENU_ID_DELETE = 3;
    private ArrayList<Book> BookList = new ArrayList<>();
    private BookFragment.BookAdapter bookAdapter;

    private ActivityResultLauncher<Intent> addDataLauncher =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
                    ,result -> {
                        if(null!=result){
                            Intent intent=result.getData();
                            if(result.getResultCode()== EditBookActivity.RESULT_CODE_SUCCESS)
                            {
                                Bundle bundle=intent.getExtras();
                                String title= bundle.getString("title");
                                int position = bundle.getInt("position");
                                BookList.add(position, new Book(title,R.drawable.book_no_name) );
                                new DataSaver().Save(this.getContext(),BookList);
                                bookAdapter.notifyItemInserted(position);
                            }
                        }
                    });


    private ActivityResultLauncher<Intent> updateDataLauncher =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
                    ,result -> {
                        if(null!=result){
                            Intent intent=result.getData();
                            if(result.getResultCode()== EditBookActivity.RESULT_CODE_SUCCESS)
                            {
                                Bundle bundle=intent.getExtras();
                                String title= bundle.getString("title");
                                int position = bundle.getInt("position");
                                BookList.get(position).setTitle(title);
                                new DataSaver().Save(this.getContext(),BookList);
                                bookAdapter.notifyItemChanged(position);
                            }
                        }
                    });



    public BookFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment BookFragment.
     */
    public static BookFragment newInstance() {
        BookFragment fragment = new BookFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_book, container, false);

        DataSaver dataSaver=new DataSaver();
        BookList=dataSaver.Load(this.getContext());
        if(BookList.size()==0) {
            getListBooks();
        }


        RecyclerView recyclerView = rootView.findViewById(R.id.recycle_view_books);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
        recyclerView.setLayoutManager(layoutManager);
        bookAdapter = new BookAdapter(BookList);
        recyclerView.setAdapter(bookAdapter);
        return rootView;
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId())
        {
            case MENU_ID_ADD:
                Intent intent=new Intent(this.getContext(), EditBookActivity.class);
                intent.putExtra("position",item.getOrder());
                addDataLauncher.launch(intent);
                break;
            case MENU_ID_UPDATE:
                Intent intentUpdate=new Intent(this.getContext(), EditBookActivity.class);
                intentUpdate.putExtra("position",item.getOrder());
                intentUpdate.putExtra("title",BookList.get(item.getOrder()).getCoverResourceName());
                intentUpdate.putExtra("cover",BookList.get(item.getOrder()).getCoverResourceId());
                updateDataLauncher.launch(intentUpdate);
                break;
            case MENU_ID_DELETE:
                AlertDialog alertDialog;
                alertDialog = new AlertDialog.Builder(this.getContext())
                        .setTitle(R.string.confirmation)
                        .setMessage(R.string.sure_to_delete)
                        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                BookList.remove(item.getOrder());
                                new DataSaver().Save(BookFragment.this.getContext(),BookList);
                                bookAdapter.notifyItemRemoved(item.getOrder());
                            }
                        }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {}
                        }).create();
                alertDialog.show();
                break;
        }
        return super.onContextItemSelected(item);
    }

    public void getListBooks() {
        BookList.add(new Book("软件项目管理案例教程（第4版）", R.drawable.book_2));
        BookList.add(new Book("创新工程实践", R.drawable.book_no_name));
        BookList.add(new Book("信息安全数学基础（第2版）", R.drawable.book_1));
    }


    class BookAdapter extends RecyclerView.Adapter<BookAdapter.ViewHolder> {

        private final List<Book> mBookList;

        public BookAdapter(List<Book> bookList) {
            mBookList = bookList;
        }

        class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            ImageView bookImage;
            TextView bookName;

            public ViewHolder(View view) {
                super(view);
                bookImage = view.findViewById(R.id.image_view_book_cover);
                bookName = view.findViewById(R.id.text_view_book_title);

                view.setOnCreateContextMenuListener(this);
            }

            @Override
            public void onCreateContextMenu
                    (ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                contextMenu.add(0,MENU_ID_ADD,getAbsoluteAdapterPosition(),"Add a new book.");
                contextMenu.add(0,MENU_ID_UPDATE,getAbsoluteAdapterPosition(),"Update this book.");
                contextMenu.add(0,MENU_ID_DELETE,getAbsoluteAdapterPosition(),"Delete this book.");
            }
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,viewGroup,false);
            ViewHolder holder = new ViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Book book = mBookList.get(position);
            holder.bookImage.setImageResource(book.getCoverResourceId());
            holder.bookName.setText(book.getCoverResourceName());
        }

        @Override
        public int getItemCount() {
            return mBookList.size();
        }
    }

}